package lib.bone.common.converter;

import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.setting.dialect.Props;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.nio.charset.StandardCharsets;

/**
 * @Author Kindear
 * @Date 2021-09-24
 * @AES 对称加密转换器
 */
public class EncryptConverter implements AttributeConverter<String,String> {
    public EncryptConverter() {
        super();
    }

    @Override
    public String convertToDatabaseColumn(String content) {
        Props props = new Props("application.properties");
        /**对数据进行加密，返回密文存储到数据库中**/
        //byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        // 密钥长度需要满足 16 位
        byte[] key = props.getProperty("bone.aes.key").getBytes(StandardCharsets.UTF_8);
//        System.out.println("key is : "+key.length);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

        String encryptHex = aes.encryptHex(content);

        return encryptHex;
    }

    @Override
    public String convertToEntityAttribute(String s) {

        Props props = new Props("application.properties");
        /**对数据进行加密，返回密文存储到数据库中**/
        //byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        byte[] key = props.getProperty("bone.aes.key").getBytes(StandardCharsets.UTF_8);

        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

        String decryptStr = aes.decryptStr(s);

        return decryptStr;
    }
}
